package zhai.docking.alipay.sync.base.bizlog;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import zhai.docking.alipay.constant.LogConstant;
import zhai.docking.alipay.domain.base.bizlog.BizLogData;
import zhai.docking.alipay.domain.base.bizlog.BizLogSave;
import zhai.docking.alipay.util.DateUtil;
import zhai.docking.alipay.util.JSONUtil;
import zhai.docking.alipay.util.ObjectUtil;
import zhai.docking.alipay.util.StringUtil;

/**
 * @author Created by 翟凤玺
 * @package zhai.docking.alipay.sync.base.bizlog
 * @project-name zhai-docking-alipay
 * @description 业务日志持久化 服务
 * @create-datetime 2020-8-28 11:27
 */
@Slf4j
@Service
public class BizLogAsync {


    private static final String BUSINESS_NAME = "【异步 业务日志持久化 服务】";
    private static final String METHOD_MONGODB = "（mongodb存储）";

    @Autowired
    MongoTemplate mongoTemplate;

    @Async
    public void mongodb(BizLogSave in) {
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_MONGODB, LogConstant.IN, JSONUtil.toStr(in)));
        BizLogData copy = ObjectUtil.copy(in, BizLogData.class);
        if (StringUtil.isBlank(in.getId())) {
            /** 新增 */
            copy.setDateTime(DateUtil.fmtLocalDateTimeToStr(DateUtil.getCurrentLocalDateTime(), DateUtil.DATETIME_FMT_4));
            mongoTemplate.insert(copy, in.getDbName());
        } else {
            BizLogData data = mongoTemplate.findById(in.getId(), BizLogData.class, in.getDbName());
            if (ObjectUtil.isNotNull(data)) {
                /** 修改 */
                Query query = new Query(Criteria.where("_id").is(in.getId()));
                Update update = new Update();
                update.push("data", copy.getData());
                update.push("dateTime", DateUtil.fmtLocalDateTimeToStr(DateUtil.getCurrentLocalDateTime(), DateUtil.DATETIME_FMT_4));
                mongoTemplate.updateMulti(query, update, in.getDbName());
            }
        }
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_MONGODB, LogConstant.RESULT, LogConstant.SUCCESS));
    }
}